package com.mapull.simple;

import java.util.Arrays;

/**
 * 选择排序
 * @author mapull
 * @date 2022-06-05
 */
public class Selection {

    public static void main(String[] args) {
        int[] nums = {5,9,7,4,6,1,3,2,8};
        System.out.println("排序前 " + Arrays.toString(nums));
        selectionSort(nums);
        System.out.println("排序后 " + Arrays.toString(nums));
    }

    private static void selectionSort(int[] nums) {
        // i 表示每轮选择最小元素需要交换到的位置
        for (int i = 0; i < nums.length - 1; i++) {
            // 最小元素的索引需要暂存
            int min = i;
            for (int j = min + 1; j < nums.length; j++) {
                if(nums[min] > nums[j]){
                    min = j;
                }
            }
            if(min != i){
                System.out.println("交换 " + nums[min] + " 与 " + nums[i] + "; ");
                swap(nums, min, i);
            }
        }
    }

    private static void swap(int[] nums, int m, int n) {
        int tmp = nums[m];
        nums[m] = nums[n];
        nums[n] = tmp;
    }
}
